import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/ui/login/login_viewmodel.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key, required this.viewModel});
  final LoginViewModel viewModel;

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    widget.viewModel.login.addListener(_onLoginResult);
  }

  @override
  void didUpdateWidget(covariant LoginScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    oldWidget.viewModel.login.removeListener(_onLoginResult);
    widget.viewModel.login.addListener(_onLoginResult);
  }

  @override
  void dispose() {
    widget.viewModel.login.removeListener(_onLoginResult);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              AppLocalizations.of(context)!.welcome,
              style: Theme.of(context).textTheme.displayLarge,
            ),
            const SizedBox(height: 16),
            Form(
              key: _formKey,
              child: Column(
                children: [
                  SizedBox(
                    width: 300,
                    child: TextFormField(
                      decoration: InputDecoration(
                        hintText: AppLocalizations.of(context)!.username,
                      ),
                      controller: _usernameController,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return AppLocalizations.of(context)!.enter_username;
                        }
                        return null;
                      },
                    ),
                  ),
                  const SizedBox(height: 16),
                  ListenableBuilder(
                      listenable: widget.viewModel,
                      builder: (context, _) {
                        return SizedBox(
                          width: 300,
                          child: TextFormField(
                            decoration: InputDecoration(
                              hintText: AppLocalizations.of(context)!.password,
                              suffixIcon: IconButton(
                                icon: widget.viewModel.showPassword ? const Icon(Icons.visibility_off) : const Icon(Icons.visibility),
                                onPressed: () {
                                  widget.viewModel.taggleShowPassword();
                                },
                              ),
                            ),
                            obscureText: !widget.viewModel.showPassword, // hide the password
                            controller: _passwordController,
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return AppLocalizations.of(context)!.enter_password;
                              }
                              return null;
                            },
                          ),
                        );
                      }),
                  const SizedBox(height: 32),
                  ListenableBuilder(
                      listenable: widget.viewModel.login,
                      builder: (context, _) {
                        if (widget.viewModel.login.running) {
                          return SizedBox(
                            width: 300,
                            child: ElevatedButton.icon(
                              onPressed: () {},
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Theme.of(context).colorScheme.secondary,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(4),
                                ),
                              ),
                              icon: const SizedBox(
                                width: 12,
                                height: 12,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                ),
                              ),
                              label: Text(
                                AppLocalizations.of(context)!.login,
                                style: TextStyle(fontWeight: FontWeight.bold),
                              ),
                            ),
                          );
                        }
                        return SizedBox(
                          width: 300,
                          child: ElevatedButton(
                            onPressed: () {
                              if (_formKey.currentState!.validate()) {
                                widget.viewModel.login.execute(
                                  (_usernameController.text, _passwordController.text),
                                );
                              }
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Theme.of(context).colorScheme.secondary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(4),
                              ),
                            ),
                            child: Text(
                              AppLocalizations.of(context)!.login,
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        );
                      }),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onLoginResult() {
    if (widget.viewModel.login.completed) {
      final from = GoRouterState.of(context).uri.queryParameters['from'];
      if (from != null) {
        context.pushReplacement(from);
      } else {
        context.go('/catalog');
      }
    }
    if (widget.viewModel.login.error) {
      var result = widget.viewModel.login.result as Error<void>;
      widget.viewModel.login.clearResult();
      ScaffoldMessenger.of(context)
        ..clearSnackBars()
        ..showSnackBar(
          SnackBar(
            content: Text(result.errorMessage()),
          ),
        );
    }
  }
}
